/*
 * Copyright 2008 Georgi Staykov
 * 
 * This file is part of pscoder.
 *
 * pscoder is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * pscoder is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with pscoder.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.gstaykov.pscoder.preferences;

import java.util.ArrayList;
import java.util.StringTokenizer;

import org.eclipse.jface.preference.ListEditor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;

public class FileEditor extends ListEditor {

    private String[] extensionsFilter;
    
    public FileEditor(String name, String labelText, Composite parent) {
        super(name, labelText, parent);
    }
    
    public FileEditor(String name, String labelText, Composite parent, String[] extensionsFilter) {
        super(name, labelText, parent);
        this.extensionsFilter = extensionsFilter;
    }

    @Override
    protected String createList(String[] items) {
        StringBuffer sb = new StringBuffer("");
        
        for (int i = 0; i < items.length - 1; i++) {
            sb.append(items[i]).append(PreferenceConstants.SNAPIN_FILES_SEPARATOR);
        }
        
        if (items.length != 0) {
            sb.append(items[items.length - 1]);
        }
        
        return sb.toString();
    }

    @Override
    protected String getNewInputObject() {
        FileDialog dialog = new FileDialog(getShell());

        dialog.setFilterExtensions(extensionsFilter);
        String selectedFile = dialog.open();
        
        if (selectedFile != null) {
            selectedFile = selectedFile.trim();
            if (selectedFile.length() == 0) {
                return null;
            }
            
            return selectedFile;
        }
        
        return null;
    }

    @Override
    protected String[] parseString(String stringList) {
        StringTokenizer st = new StringTokenizer(stringList, PreferenceConstants.SNAPIN_FILES_SEPARATOR);
        ArrayList<String> elements = new ArrayList<String>();
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (token.length() != 0) {
                elements.add(token);
            }
        }
        return elements.toArray(new String[elements.size()]);
    }

}
